package com.iuie.ns.datum.service.impl;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.iuie.ns.datum.mapper.TableStructureMapper;
import com.iuie.ns.datum.service.ITableFieldService;
import com.iuie.ns.datum.service.ITableStructureService;
import com.iuie.ns.datum.vo.TableChangeHistoryVO;
import com.iuie.ns.datum.vo.TableStructureVO;
import com.iuie.ns.frame.exception.ServiceException;
import com.iuie.ns.frame.utils.ListUtils;
import com.iuie.ns.frame.utils.ShiroUtils;
import com.iuie.ns.frame.utils.StringUtils;
import com.iuie.ns.frame.web.dataset.vo.Page;
import com.iuie.ns.system.vo.user.SysUserVO;

@Service("tableStructureService")
public class TableStructureServiceImpl implements ITableStructureService {
	
	@Resource
	private TableStructureMapper tableStructureMapper;
	
	@Resource
	private ITableFieldService tableFieldService;

	@Override
	public List<TableStructureVO> findByPage(Page page, TableStructureVO condition) {
		PageHelper.startPage(page.getPage(), page.getRows(), true);
		List<TableStructureVO> list = tableStructureMapper.findByCondition(condition);
		page.loadData(list);
		return list;
	}
	
	@Override
	public TableStructureVO findById(Long id) {
		return tableStructureMapper.findById(id);
	}

	@Override
	public void deleteTableStructure(Long id) {
		// 1.删除表实例的字段
		tableFieldService.deleteFieldsByTableId(id);
		// 2.删除表的变更记录
		tableStructureMapper.deleteTableChangeHisotry(id);
		// 3.删除表实例
		tableStructureMapper.deleteById(id);
	}

	@Override
	public void saveTableStructure(TableStructureVO table, String updateRemark) {
		if (table == null) {
			throw new ServiceException("保存表失败，没有数据可保存！");
		}
		if (table.getProjectId() == null) {
			throw new ServiceException("保存表失败，所属项目不能为空！");
		}
		if (StringUtils.isBlank(table.getEnTableName())) {
			throw new ServiceException("保存表失败，表英文名不能为空！");
		}
		if (StringUtils.isBlank(table.getCnTableName())) {
			throw new ServiceException("保存表失败，表中文名不能为空！");
		}
		TableStructureVO mItem = this.findByEnTableNameAndProjectId(table.getEnTableName(), table.getProjectId());
		if (mItem != null) {
			if (table.getId() == null || (table.getId() != null && table.getId().compareTo(mItem.getId()) != 0)) {
				throw new ServiceException("保存表失败，相同的项目下存在同名的表（英文名）【" + mItem.getEnTableName() + "】！");
			}
		}
		// enTableName转大写
		String enTableName = table.getEnTableName();
		table.setEnTableName(StringUtils.upperCase(enTableName));
		
		SysUserVO user = (SysUserVO) ShiroUtils.getCurrentUser();
		String userId = user.getUserId();
		String userName = user.getUserName();
//		String userId = "10000001";
//		String userName = "刘杰";
		
		if (table.getId() == null) {
			// 新增
			table.setId(System.currentTimeMillis());
			table.setCreatorId(userId);
			table.setCreatorName(userName);
			table.setCreateTime(new Date());
			tableStructureMapper.addOne(table);
		} else {
			// 修改
			tableStructureMapper.updateOne(table);
			this.addUpdateHistory(updateRemark, table.getId());
		}
	}

	@Override
	public void addUpdateHistory(String updateRemark, Long tableId) {
		if (StringUtils.isBlank(updateRemark)) {
			throw new ServiceException("更新失败，更新备注不能为空！");
		}
		SysUserVO user = (SysUserVO) ShiroUtils.getCurrentUser();
		String userId = user.getUserId();
		String userName = user.getUserName();
//		String userId = "10000001";
//		String userName = "刘杰";
		TableChangeHistoryVO his = new TableChangeHistoryVO();
		his.setId(System.currentTimeMillis());
		his.setRemark(updateRemark);
		his.setTableId(tableId);
		his.setUpdateTime(new Date());
		his.setUpdateUserId(userId);
		his.setUpdateUserName(userName);
		tableStructureMapper.addUpdateHistory(his);
	}

	@Override
	public List<TableChangeHistoryVO> findChangeHistory(Long tableId) {
		if (tableId == null) {
			return null;
		}
		return tableStructureMapper.findChangeHistory(tableId);
	}

	@Override
	public List<TableChangeHistoryVO> findChangeHistoryByPage(Long tableId, Page page) {
		if (tableId == null) {
			return null;
		}
		PageHelper.startPage(page.getPage(), page.getRows(), true);
		List<TableChangeHistoryVO> list = tableStructureMapper.findChangeHistory(tableId);
		page.loadData(list);
		return list;
	}

	@Override
	public void deleteTableStructureByProjectId(Long projectId) {
		List<TableStructureVO> list = tableStructureMapper.findByProjectId(projectId);
		if (ListUtils.isNotEmpty(list)) {
			Iterator<TableStructureVO> it = list.iterator();
			while(it.hasNext()) {
				TableStructureVO table = it.next();
				Long tableId = table.getId();
				this.deleteTableStructure(tableId);
			}
		}
	}

	@Override
	public TableStructureVO findByEnTableNameAndProjectId(String enTableName, Long projectId) {
		TableStructureVO condition = new TableStructureVO();
		condition.setEnTableName(enTableName);
		condition.setProjectId(projectId);
		List<TableStructureVO> list = tableStructureMapper.findByCondition(condition);
		if (list.size() == 1) {
			return list.get(0);
		}
		return null;
	}
	

}
